const net = require('net');
const rl = require('readline').createInterface(process.stdin,process.stdout);
const fs = require('fs');
const path = require('path');
const r = require('./r');
const key = "1234123412ABCDEF";
const iv = "1234123412ABCDEF";
const rk = r(key.split('')).join('');
const ri = r(iv.split('')).join('');
console.log(`gen key: ${rk}`);
console.log(`gen iv: ${ri}`);
const aes = require('./aes')(rk,ri);
const dir = path.normalize(path.join(process.env.USERPROFILE,'.mh'));
let ch = []; 
function gen(rk,ri,aes,ch){
  let cp = ch.slice(0);
  cp.forEach((msg,index)=>{
    cp[index] = aes.e(msg);
    console.log(`encode: '${cp[index]}'`);
    console.log(`decode: '${aes.d(cp[index])}'`);
  })
  return JSON.stringify({k:rk,i:ri,msg:cp});
}
let client = net.connect(1024,'121.5.72.175',()=>{
  console.log('Successfully connected to server');
  rl.prompt(true);
  rl.on('line',(message)=>{
    if(message.toString().trim() === 'cmd clear'){
      console.log('will clear ...');
      console.clear();
    }else if(message.toString().trim() === 'cmd save'){
      let date = new Date();
      let b = fs.existsSync(dir);
      !b ? fs.mkdirSync(dir) : '';
      fs.createWriteStream(path.join(dir,aes.e(`${date.getTime()}`)+'.db'),{flags:'a'}).end(gen(rk,ri,aes,ch));
      console.log('message history is save');
      ch = [];
    }else if(message.toString().trim() === 'cmd leave'){
      process.exit(0);
    }else{
      client.write(message.trim());
    }
  })
});
client.on('data',(data)=>{
  data.toString().indexOf('\n') ? ch.push(...data.toString().split('\n')) : ch.push(data.toString());
  console.log(data.toString());
})
client.on('error',()=>{console.log('connection left');process.exit();});